module.exports = app => {
  const route = require('express').Router({
    mergeParams: true
  })
  const AdminUser = require('../../models/AdminUser')
  const bcrypt = require('bcryptjs')
  const jwt = require('jsonwebtoken')
  const util = require('../../util/util')
  const auth = require('../../middleware/middleware').auth()
  route.post('/', async (req,res)=>{
    const model = await  req.model.create(req.body)
    res.send(util.success({data:model}))
  })

  route.put('/:id',async(req,res)=>{
    const model = await req.model.findByIdAndUpdate(req.params.id,req.body)
    res.send(util.success({data:model}))
  })
  route.delete('/:id',async (req,res) => {
    await req.model.findByIdAndDelete(req.params.id)
    
    res.send(util.success({}))
  })
  route.get('/',auth,async (req,res)=>{
    let query = {}
    let options = {}
    if(req.model.modelName === 'Category'){
      options.populate = 'parents'
    }
    if(req.model.modelName === 'Item'){
      options.populate = 'category'
    }
    query = {
      ... req.query
    }

    const items = await req.model.find(query).setOptions(options).limit(10)
    res.send(util.success({data:items}))

  })
  

  route.get('/:id',async (req,res)=>{
    
    const model = await req.model.findById(req.params.id)
    res.send(util.success({data:model}))
  })
  route.get('/ids/:ids',async (req,res)=>{
    let arr = req.params.ids.split(',')

    const model = await req.model.find({
      _id:{
        $in: arr
      }
    })
    res.send(util.success({data:model}))
  })
  app.use('/admin/api/rest/:resource',(req,res,next)=>{
    let modelName = require('inflection').classify(req.params.resource)
    const Model = require(`../../models/${modelName}`)
    req.model = Model
    next()
  },route)
  const multer = require('multer')
  const upload = multer({
    dest: __dirname + '/../../../uploads/'
  })
  app.post('/admin/api/upload',upload.single('file'),(req,res)=>{
    const file = req.file
    file.url = `http://admin.wxwiki.net/uploads/${file.filename}`
    res.send(util.success({data:file}))
  })

  app.post('/admin/api/login',async function(req,res){
      const {username,password} = req.body
      const user = await AdminUser.findOne({username}).select('password')
      if(user){
        const passTruth = bcrypt.compareSync(password,user.password)
        if(passTruth){
          const token = jwt.sign({_id:user._id},req.app.get('secret'))
          res.send(util.success({data:{token}}))
        }else{
          res.send(util.fail({message:'账号密码错误'}))
        }
      }else{
        res.send(util.fail({message: '用户不存在'}))
      }
     
  })
  
}